package com.example.thread.base.a1b2c3;

/**
 * @author LiYuhang
 * @version 0.1
 * @application
 * @Date 2021/6/28 12:01
 * @Description 使用CAS+volatile的方式打印
 */
public class Print_CAS {
    enum ReadyToRun {T1, T2}

    //线定义T1准备运行，而且要设置volatile线程可见
    static volatile ReadyToRun r = ReadyToRun.T1;
    public static void main(String[] args) {
        char[] num = "1234567".toCharArray();
        char[] str = "ABCDEFG".toCharArray();

        new Thread(() -> {
            for (char n : str) {
                //如果不是T1线程运行就一直返回为空，直到T1运行打印，打印完之后把准备运行的变为T2
                while (r != ReadyToRun.T1) {
                }
                System.out.println(n);
                r = ReadyToRun.T2;

            }
        }, "t1").start();

        new Thread(() -> {
            for (char s : num) {
                //如果不是T1线程运行就一直返回为空，直到T1运行打印，打印完之后把准备运行的变为T2
                while (r != ReadyToRun.T2) {
                }
                System.out.println(s);
                r = ReadyToRun.T1;

            }
        }, "t1").start();
    }

}
